﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.Caching;
using System.Web.Hosting;
using System.IO;
using Ue.Core;
using Ue.Components.FileWatcher;

namespace Ue.Infrastructure.Caching.VolatileProvider
{
    public interface IFileMonitor
    {
        IVolatileToken WhenPathChanges(string path);
    }

    public class FileMonitor : IFileMonitor
    {
        private readonly Thunk thunk;
        private readonly IDictionary<string, Weak<Token>> tokens = new Dictionary<string, Weak<Token>>();

        public static int cached = 0;
        private IFileMonitorManager fileMonitorManager;

        public FileMonitor(IFileMonitorManager fileMonitorManager)
        {
            this.thunk = new Thunk(this);
            this.fileMonitorManager = fileMonitorManager;
        }

        public IVolatileToken WhenPathChanges(string path)
        {
            try
            {
                if (!File.Exists(path)
                    && !Directory.Exists(path))
                {
                    return new Token(path);
                }

                var token = this.BindToken(path);

                this.BindSignal(path);

                return token;
            }
            catch
            {
                return new Token(path);
            }
        }

        public IVolatileToken WhenVirtualPathChanges(string virtualPath)
        {
            return this.WhenPathChanges(
                HostingEnvironment.MapPath(virtualPath));
        }

        public void Signal(string path)
        {
            var token = this.DetachToken(path);
            if (token != null)
            {
                token.IsCurrent = false;
            }
        }

        /// <summary>
        /// 将Token绑定到集合中的Weak对象
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private Token BindToken(string path)
        {
            lock (this.tokens)
            {
                Weak<Token> weak;
                if (!this.tokens.TryGetValue(path, out weak))
                {
                    weak = new Weak<Token>(new Token(path));

                    this.tokens[path] = weak;
                }

                //因为有一些weak的token可能被分离了，所以不存在了。这里需要绑定一下。
                var token = weak.Target;
                if (token == null)
                {
                    token=new Token(path);
                    weak.Target = token;
                }

                return token;
            }
        }

        private void BindSignal(string path)
        {
            this.BindSignal(path, this.thunk.Signal);

        }

        private void BindSignal(string path, Action<string> callback)
        {
            Action<Components.FileWatcher.IFileMonitor> fileWatchCallBack = (state) =>
            {
                callback(path);
                ++cached;
            };

            this.fileMonitorManager.TryAcquireMonitor(path, fileWatchCallBack);
            
        }

        /// <summary>
        /// 将token从集合中的Weak分离
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private Token DetachToken(string path)
        {
            lock (this.tokens)
            {
                Weak<Token> weak;
                if (!this.tokens.TryGetValue(path,out weak))
                {
                    return null;
                }

                var token = weak.Target;
                weak.Target = null;
                return token;
            }
        }

        public class Token : IVolatileToken
        {
            public Token(string path)
            {
                this.IsCurrent = true;
                this.Path = path;
            }

            public bool IsCurrent { get; set; }

            public string Path { get; private set; }

            public override string ToString()
            {
                return string.Format("IsCurrent: {0}, VirtualPath: \"{1}\"", IsCurrent, Path);
            }
        }

        class Thunk
        {
            private readonly Weak<FileMonitor> week;

            public Thunk(FileMonitor virtualPathMonitor)
            {
                this.week = new Weak<FileMonitor>(virtualPathMonitor);
            }

            public void Signal(string path)
            {
                var provider = this.week.Target;
                if (provider != null)
                {
                    provider.Signal(path);
                }
            }
        }
    }
}
